package com.itlaobing.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itlaobing.listener.UserListener;
import com.itlaobing.model.UserInfo;

/**
 * 消息相关Servlet
 * @author Ma_Hao
 *
 */
// servlet映射路径为 /message
@WebServlet("/messages")
public class Message extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private Logger log = Logger.getLogger(this.getClass().getName());

	/**
	 * 重写doGet及doPost方法 并将接收到的Http请求都发送到processRequest方法中做处理
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
     * 自定义processRequest方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
		String action = request.getParameter("action");
        if ("loginRoom".equals(action)) {	//登录时，写入系统公告
            this.loginRoom(request, response);
        } else if ("sendMessage".equals(action)) {	//发送聊天信息
            this.sendMessages(request, response);
        }
    }

	// 登录时，写入系统公告
	public void loginRoom(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		HttpSession session = request.getSession();
		String username = request.getParameter("username"); // 获得登录用户名
		UserInfo user = UserInfo.getInstance(); // 获得UserInfo类的对象
		session.setMaxInactiveInterval(600); // 设置Session的过期时间为10分钟
		Vector vector = user.getList(); // 获取登录过的用户列表
		boolean flag = true; // 标记是否登录的变量，true表示未登录过
		// 判断用户是否登录
		log.info("vector的size：" + vector.size());
		// 如果登录用户数量大于0，判断当前用户是否已登录
		if (vector != null && vector.size() > 0) {
			for (int i = 0; i < vector.size(); i++) {
				// elementAt 返回指定索引处的对象
				log.info("vector" + i + ":" + vector.elementAt(i) + " user:" + username);
				if (username.equals(vector.elementAt(i))) {
					// PrintWriter向页面输出流打印对象
					PrintWriter out;
					try {
						out = response.getWriter();
						out.println(
								"<script language='javascript'>alert('该用户已经登录');window.location.href='index.jsp';</script>");
					} catch (IOException e) {
						e.printStackTrace();
					}
					flag = false;
					break;
				}
			}
		}
		// 如果没有登录过，保存用户信息
		if (flag) {
			UserListener ul = new UserListener(); // 创建UserListener的对象
			ul.setUser(username); // 添加用户
			user.addUser(ul.getUser()); // 添加用户到UserInfo类的对象中
			session.setAttribute("user", ul); // 将UserListener对象绑定到Session中
			session.setAttribute("username", username); // 保存当前登录的用户名
			session.setAttribute("loginTime", new Date().toLocaleString()); // 保存登录时间
			// 获取ServletContext对象，这里有所的消息都放在ServletContext的message属性中
			ServletContext application = getServletContext();
			String sourceMessage = "";
			if (null != application.getAttribute("message")) {
				// 获取之前的message信息
				sourceMessage = application.getAttribute("message").toString();
			}
			// 拼接用户登录的消息
			sourceMessage += "系统公告：<font color='gray'>" + username + "走进了聊天室！</font><br>";
			// 将所有的消息重新放到message属性中去
			application.setAttribute("message", sourceMessage);
			try {
				// 转发到login_ok.jsp页面
				response.sendRedirect("main.jsp");
			} catch (Exception ex) {
				log.log(Level.SEVERE, null, ex);
			}
		}
	}

	// 发送聊天信息
	public void sendMessages(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		Random random = new Random();
		String from = request.getParameter("from"); // 发言人
		String face = request.getParameter("face"); // 表情
		String to = request.getParameter("to"); // 接收者
		String color = request.getParameter("color"); // 字体颜色
		String content = request.getParameter("content"); // 发言内容
		String sendTime = new Date().toLocaleString(); // 发言时间
		ServletContext application = getServletContext();
		//获取之前的信息
		String sourceMessage = application.getAttribute("message").toString();
		try {
			// 发言时间
			sourceMessage += "<font color='blue'><strong>" + from + "</strong></font><font color='#CC0000'>" + face
					+ "</font>对<font color='green'>[" + to + "]</font>说：" + "<font color='" + color + "'>" + content
					+ "</font>（" + sendTime + "）<br>";
			application.setAttribute("message", sourceMessage);
			request.getRequestDispatcher("content.jsp?nocache=" + random.nextInt(10000))
					.forward(request, response);
		} catch (Exception ex) {
			log.log(Level.SEVERE, null, ex);
		}

	}
}
